<template>
  <gzhb-page
    title="进度汇报"
    btn-name="提交"
    @click="submitHB">
    <div class="scroll">   
      <gzhb-field 
        label-width="30%" 
        label="任务名称："
        @click="isShowBaseInfo = true">
        <van-field readonly slot="input" v-model="form.taskName" rows="1" autosize type="textarea" placeholder="" />
        <template slot="right">
          <span class="ui-icon ui-icon__more"></span>
        </template>
      </gzhb-field>
      <gzhb-field label-width="30%" label="汇报时间：">
        <van-field slot="input" v-model="form.rptDate" rows="1" autosize type="textarea" placeholder="请输入" />
      </gzhb-field>
      <gzhb-field label-width="30%" label="汇报内容：">
        <van-field  slot="input" v-model="form.reportContent" rows="1" autosize type="textarea" placeholder="请输入" />
      </gzhb-field>
      <gzhb-field label-width="30%" label="存在问题：">
        <van-field slot="input" v-model="form.problem" rows="1" autosize type="textarea" placeholder="请输入" />
      </gzhb-field>
      <gzhb-field label-width="30%" label="下一步措施：">
        <van-field slot="input" v-model="form.nextStep" rows="1" autosize type="textarea" placeholder="请输入" />
      </gzhb-field>
      <gzhb-field label-width="30%" label="进度：">
        <van-field
          slot="input"
          v-model="form.compPct"
          rows="1"
          autosize
          type="textarea"
          placeholder="请输入数字"
          @input="handleFormate"/>
        <template slot="right">
          <span
            v-show="form.compPct.length"
            :style="[{
              position: 'absolute',
              top: '0',
              left: finishIconPosition
            }]">%</span>
        </template>
      </gzhb-field>
      <gzhb-field
        v-if="form.compPct == 100"
        label-width="30%"
        label="完成时间："
        readonly
        placeholder="请选择"
        v-model="form.finishTime"
        @click="pickTime.show = true">
      </gzhb-field>
      <hr class="ui-hr" />

      <div class="ui-group">
        <div class="ui-group__title">交付物（附件）</div>
        <div class="ui-group__body">
          <!-- <div class="gzhb_tip">您还未上传图片</div> -->
          <ul class="gzhb-fjlist">
            <li v-for="(item, index) in files">
              <span class="ui-icon" :class="item.fType | fileIcon"></span>
              <span class="desc">{{item.name}}</span>
              <span class="type">{{item.type | fileSubmitTyp}}</span>
              <span @click="handleShutFile(index)" class="ui-icon ui-icon__delete" style="font-size: 3.6vw; margin-left: 4px"></span>
            </li>
          </ul>
          <div class="ui-cell">
            <button @click="upload.dialog = true" class="gzhb-add">
              <span class="ui-icon ui-icon__add"></span>
              <span class="name">添加附件</span>
            </button>
          </div>
        </div>
      </div>

      <gzhb-dialog :visible.sync="upload.dialog" title="选择类型">
        <div v-if="shifouxxjd" class="ui-cell">
          <gzhb-radio v-model="upload.submitTypes" label="xxjd">形象进度</gzhb-radio>
        </div>
        <div class="ui-cell">
          <gzhb-radio v-model="upload.submitTypes" label="-1">其他</gzhb-radio>
        </div>
        <div class="ui-row ui-border__top">
          <div class="ui-col ui-col4 ui-col__offset4">
            <div class="ui-cell">
              <button @click="handleUpload" class="ui-button ui-whole-line">上传文件</button>
            </div>
          </div>
        </div>
      </gzhb-dialog>
    </div>
    <input ref="upfile" style="display: none" @change="fileChange" type="file">

    <!-- 过程详情弹窗 -->
    <gzhb-dialog
      :visible.sync="isShowBaseInfo"
      title="基本信息">
      <gzhb-field
        labelWidth="32%"
        label="任务状态：">
        <van-field readonly rows="1" slot="input" v-model="baseInfo.statLabel" autosize type="textarea" placeholder='' />
      </gzhb-field>
      <gzhb-field
        labelWidth="32%"
        label="结算类型：">
        <van-field readonly rows="1" slot="input" v-model="baseInfo.settleTypeName" autosize type="textarea" placeholder='' />
      </gzhb-field>
      <gzhb-field
        v-if="baseInfo.slaveDescription"
        labelWidth="32%"
        label="任务描述：">
        <van-field 
          slot="input" 
          rows="1" 
          type="textarea" 
          readonly 
          autosize 
          v-model="baseInfo.slaveDescription" 
          placeholder='' />
      </gzhb-field>
      <gzhb-field
        v-if="baseInfo.describe"
        labelWidth="32%"
        label="交付物要求：">
        <van-field 
          slot="input" 
          rows="1" 
          type="textarea" 
          readonly 
          autosize 
          v-model="baseInfo.describe" 
          placeholder='' />
      </gzhb-field>
    </gzhb-dialog>

    <!-- 时间选择 -->
    <van-popup v-model="pickTime.show" position="bottom">
      <van-datetime-picker
        v-model="pickTime.time"
        type="date"
        @cancel="pickTime.show = false"
        @confirm="pickTimeConfirm"/>
    </van-popup>

    <!-- loading -->
    <gzhb-loading :isShow="isLoading"></gzhb-loading>
  </gzhb-page>
</template>

<script>
  import axios from '@/axios'
  import moment from 'moment'
  import { onNextFrame, utils_fileIcon, utils_fileType, utils_fileSubmitTyp } from "@/utils/index.js"
  export default {
    data() {
      return {
        isLoading: false,
        finishIconPosition: '6vw',
        upload: {
          dialog: false,
          submitTypes: '-1'
        },
        pickTime: {
          show: false,
          time: new Date()
        },
        formData: new FormData(),
        files: [],
        shifouxxjd: false,
        form: {
          taskId: '',
          taskName: '',
          rptDate: '',
          reportContent: '',
          problem: '',
          nextStep: '',
          compPct: '',
          finishTime: ''
        },
        isShowBaseInfo: false,
        baseInfo:{
          statLabel:'',
          settleTypeName:'',
          slaveDescription:'',
          describe:''
        }
      }
    },
    created() {
      
      const masterTask = JSON.parse(localStorage.getItem('masterTask'))
      this.baseInfo = masterTask
      this.form.taskName = masterTask.name
      this.form.taskId = localStorage.getItem('id')
      this.form.rptDate = moment(new Date()).format('YYYY-MM-DD')

      if(masterTask.shifouxxjdhb){
        this.shifouxxjd = true
      }
    },
    filters: {
      fileIcon: utils_fileIcon,
      fileType: utils_fileType,
      fileSubmitTyp: utils_fileSubmitTyp
    },
    methods: {
      fileChange(ev) {
        const file = ev.target.files[0]
        let position = file.name.lastIndexOf('.') + 1

        let isPic = this.handleIsPic(file.name.substr(position))

        // 当前任务是形象进度汇报，选择形象进度进行上传非图片文件时，则不加入上传队列
        if(
          this.upload.submitTypes === '-1' ||
          !this.shifouxxjd || 
          (this.shifouxxjd && isPic)
        ){
          this.files.push({
            file: file,
            fType: file.name.substr(position),
            type: this.upload.submitTypes,
            name: file.name
          })
        } else {
          this.$toast('形象进度请选择图片')
        }

        this.upload.dialog = false
        ev.target.value = ''
      },

      // 删除对应文件
      handleShutFile(index){
        this.files.splice(index, 1)
      },

      //格式化时间
      pickTimeConfirm() {
        this.form.finishTime = moment(this.pickTime.time).format('YYYY-MM-DD')
        this.pickTime.show = false
      },

      // 提交按钮
      submitHB() {    
        // 如果有内容需要提示，则禁止提交
        if(this.handleShowTip()) return

        this.isLoading = true
        const data = new FormData()
        data.append('taskId', this.form.taskId)
        data.append('taskName', this.form.taskName)
        data.append('rptDate', this.form.rptDate)
        data.append('reportContent', this.form.reportContent)
        data.append('problem', this.form.problem)
        data.append('nextStep', this.form.nextStep)
        data.append('compPct', this.form.compPct)
        data.append('finishTime', this.form.finishTime)

        this.files.forEach(item => {
          data.append('files', item.file)
          data.append('submitTypes', item.type)
        })

        axios.post('saveReport', data, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          this.isLoading = false
          if (res.success) {
            this.$toast.success('添加成功')
            this.$router.back()
          } else {
            this.$toast(res.message || '提交失败！')
          }
        })
      },

      // 对进度的文字进行控制
      handleFormate(){
        // 保证输入的是纯数字
        // 输入的范围是0-100之间
        this.form.compPct = this.form.compPct.replace(/[^\d]/g,'').substring(0, 3)
        if(this.form.compPct.indexOf(0) === 0 && this.form.compPct.length > 1){
          this.form.compPct = this.form.compPct.substring(1)
        }
        if(this.form.compPct > 100) this.form.compPct = '100'

        // %号的位置
        this.finishIconPosition = (4 + 8 * this.form.compPct.length) + 'px'
      },

      // 上传
      handleUpload(){
        this.$refs.upfile.click()
      },

      // 判断是否存在形象进度，并且存在图片
      handleJudgeXXJDPic(files){
        let isShowTip = true
        files.forEach(item=>{
          if(item.type === 'xxjd' && (item.fType === 'jpg' || item.fType === 'jpeg' || item.fType === 'png')) {
            isShowTip = false
          }      
        })       

        // 是否需要显示提示上传文件
        if(this.shifouxxjd && isShowTip){
          // this.$toast('形象进度请选择图片')
          return true
        }
      },
      
      // 上传的是否是图片
      handleIsPic(type){
        if(type === 'jpg' || type === 'jpeg' || type === 'png'){
          return true
        } else {
          return false
        }
      },

      // 内容没补充完整，则提示
      handleShowTip(){
        // 如果是形象进度汇报，形象进度没有上传图片，则禁止提交
        let isShowPicTip = this.handleJudgeXXJDPic(this.files)
        
        let tipStr = ''
        let reportContent ='，汇报内容'
        let compPct ='，进度'
        let finishTime ='，完成时间'
        let pic ='，附件'

        // 图片
        if(!isShowPicTip) pic = ''
        // 内容
        if(this.form.reportContent) reportContent = ''
        // 进度
        if(this.form.compPct) compPct = ''
        // 时间
        if(
          (this.form.compPct == 100 && this.form.finishTime) ||
          this.form.compPct < 100
        ){
          finishTime = ''
        }

        // 需要显示的提示
        tipStr = `${reportContent}${compPct}${finishTime}${pic}`
        if(tipStr){
          this.$toast(`请补充：${tipStr.slice(1)}`)
          return true
        }
      }
    }
  }
</script>

<style lang="less" scoped>
.scroll{
  height: 100%;
  overflow-y: scroll;
  .gzhb_tip{
    color: red;
    font-size: 0.14rem;
    text-align: center;
  }
  .gzhb-add {
    display: block;
    width: 100%;
    line-height: 4.375vw;
    .ui-icon {
      color: #2cadff;
      vertical-align: middle;
      font-size: 4.375vw;
      margin-right: 4px;
    }
    .name {
      font-size: 3.43vw;
      color: #2cadff;
    }
  }
}
</style>